﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace AllenalaMente.Games
{
    public partial class UITimer : UserControl
    {
        private DispatcherTimer timer = new DispatcherTimer();
        private int duration;

        public EventHandler timeOut;

        public UITimer(int duration)
        {
            InitializeComponent();

            this.duration = duration;
            timer.Interval = TimeSpan.FromSeconds(1);
            timer.Tick += new EventHandler(timer_Tick);
            PrintRemainingTime();
        }

        public void Start()
        {
            timer.Start();
        }

        public void Stop()
        {
            timer.Stop();
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            duration--;

            if (duration < 10)
                textBlockTimer.Foreground = new SolidColorBrush(Colors.Red);

            if (duration <= 0)
            {
                // Tempo scaduto
                if (timeOut != null)
                    timeOut(this, null);
            }

            PrintRemainingTime();
        }

        private void PrintRemainingTime()
        {
            string min = "" + (duration / 60) % 60;
            if (min.Length == 1) min = "0" + min;

            string sec = "" + (duration % 60);
            if (sec.Length == 1) sec = "0" + sec;

            string time = " " + min + ":" + sec + " ";
            textBlockTimer.Text = time;
        }
    }
}
